import axios from 'axios'
import {Base64} from 'js-base64';
import {ElMessageBox} from "element-plus";
import tips from '../config/Tips';

// 创建通用axios配置
let instance = axios.create({
    responseType: "json",
    timeout: 10000,
    // baseURL: "http://127.0.0.1:8000/",
    headers: {
            'content-type': 'application/json',
        }
})

// 对token加密
function baseFun() {
    const token = localStorage.getItem('token')
    // const base64 = Base64.encode(token+':')
    // return 'Basic ' + base64
    return 'Bearer' + token;
}

// http 拦截，是在axios请求发出之前给每个接口携带token
instance.interceptors.request.use(config => {
        let token = localStorage.getItem("token");
        if (token) {
            config.headers.Authorization = baseFun()
        }
        return config
    },
    err => {
        return Promise.reject(err)
    }
)

// 截，是在axios请求发出之后
instance.interceptors.response.use(
    response => {
        let code = response.data.code;
        let errData = response.data.msg;
        if (code !== 200) {
            switch (code) {
                case 401:// 没有权限
                    ElMessageBox.alert(errData, '提示', {
                        confirmButtonText: '确定',
                        type: 'error'
                    }).then(res => {
                        // 点击确定进入项
                        console.log(err)
                        window.location.href = '/'
                    }).catch(err => {
                        // 点击打叉按钮进入项
                        console.log(err)
                        window.location.href = '/'
                    })
                    break;
            }
        }
        return response
    },
    error => {
        if (error.response) {
            let ERRS = error.response.code
            let MSG = error.response.data.msg.msg
            let errData = ERRS == 401 ? MSG : '服务器发生错误';
            switch (ERRS) {
                case 401:// 没有权限
                    ElMessageBox.alert(errData, '提示', {
                        confirmButtonText: '确定',
                        type: 'error'
                    }).then(res => {
                        // 点击确定进入项
                        console.log(err)
                        window.location.href = '/'
                    }).catch(err => {
                        // 点击打叉按钮进入项
                        console.log(err)
                        window.location.href = '/'
                    })
                    break;
            }
            return Promise.reject(error.response.data.msg)
        }
        // 这个错误放开会导致页面跳到错误信息页
        return Promise.reject(error)
    }
)

export default instance